package cn.hughie.imooc;

/**
 * @Author yuh
 * @Date Created in 上午10:33 2018/5/26
 * @Description 原子计数器
 */
public class MyAtomicLong {

    private volatile long base;

    public synchronized long getVolitaleLong() {
        return base;
    }

    public long incremenAndGet() {
        long val = 0L;
        do {
            val = getVolitaleLong();
        } while (!compareAndSet(val, val + 1));
        return val + 1;
    }

    private boolean compareAndSet(long val, long l) {

        long volitaleLong = getVolitaleLong();
        synchronized (this) {
            if (volitaleLong == val) {
                base = l;
                return true;
            }
        }
        return false;
    }

}
